package com.dnjn.happiness.emo.webapi.c3v8;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson2.JSON;
import com.dnjn.happiness.common.core.http.HttpUtils;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.common.core.utils.sign.Md5Utils;
import com.dnjn.happiness.emo.webapi.c3v8.in.C3v8In;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.beans.BeanMap;

import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class C3v8Client {


    public static <T extends C3v8In> String request(String path, T in) {
        Assert.notBlank(path, "invalid.path");

        String url = C3v8Config.getHost() + path;

        in.setTimestamp(System.currentTimeMillis() / 1000);

        if (Objects.isNull(in.getPageIndex())) {
            log.warn("[warn] set pageIndex 1");
            in.setPageIndex(1);
        }
        if (Objects.isNull(in.getPageSize())) {
            log.warn("[warn] set pageSize 100");
            in.setPageSize(100);
        }
        // log.info("key:" + C3v8Config.getSecretKey());

        Map<String, Object> params = beanToMap(in);
        StringBuilder s1 = new StringBuilder();
        for (String key : params.keySet()) {
            if ("sign".equalsIgnoreCase(key) || Objects.isNull(params.get(key)) || StringUtils.isBlank(params.get(key).toString())) {
                continue;
            }
            s1.append(key).append("=").append(params.get(key)).append("&");
        }

        //E102E1DD65E859139ED8418FAA02CE8F
        //e102e1dd65e859139ed8418faa02ce8f

        s1.append("key=" + C3v8Config.getSecretKey());
        log.info("plaintext:" + s1);
        String sign = Md5Utils.hash(s1.toString()).toUpperCase();

        log.info("sign:" + sign);
        params.put("sign", sign);
        String res = HttpUtils.sendJsonPost(url, JSON.toJSONString(params));

        log.info(res);
        return res;
    }


    public static <T> Map<String, Object> beanToMap(T bean) {
        BeanMap beanMap = BeanMap.create(bean);
        Map<String, Object> map = new TreeMap<>();

        beanMap.forEach((key, value) -> {
            map.put(String.valueOf(key), value);
        });
        return map;
    }
}
